//-----------------------------------------------------------------------------------------
// ajax请求api公共基本类
define("BaseApi", ['jquery'], function ($) {
  function _ajax(opts = {
    type: null,
    contentType: null,
    url: null,
    headers: {},
    data: {},
    callback: null,
    async: true,
  }) {
    $.ajax({
      type: opts.type,
      url: opts.url,
      headers: opts.headers,
      contentType: opts.contentType,
      data: opts.data,
      async: opts.async,
      success: function (data, status) {
        if (data.errcode == 0) {
          callBack(opts.callback).onSuccess(data, status)
        } else {
          callBack(opts.callback).onError(data.errcode, data.errmsg);
        }
      },
      error: function (jqx, status, msg) {
        if (jqx.responseJSON) {
          callBack(opts.callback).onError(jqx.responseJSON.errcode, jqx.responseJSON.errmsg);
        } else {
          callBack(callback).onError(status, msg);
        }
      }
    })
  }

  function get(url, data, callback, async, headers) {
    let options = {
      type: 'get',
      url: url,
      headers: headers,
      data: data,
      callback: callback,
      async: async,
    }
    _ajax(options)
  }

  function post(url, data, callback, isForm, async, headers) {
    let content_type = 'application/x-www-form-urlencoded;charset=utf-8';
    let param = data;
    if (isForm != undefined && !isForm) {
      content_type = 'application/json;charset=utf-8';
      param = JSON.stringify(data);
    }
    let options = {
      type: 'post',
      url: url,
      contentType: content_type,
      headers: headers,
      data: param,
      callback: callback,
      async: async,
    }
    _ajax(options)
  }

  function callBack(callback) {
    if (callback == undefined || callback == null) {
      return {
        onSuccess: function (data) {
          console.log("default api success callback:", data)
        },
        onError: function (errcode, errmsg) {
          console.error("default api error callback:", errcode, errmsg)
        }
      };
    } else {
      return callback;
    }
  }
  return {
    get: get,
    post: post,
    callBack: callBack
  }
});